package net.xyuu.config;

import javax.sql.DataSource;

import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.acls.domain.AclAuthorizationStrategy;
import org.springframework.security.acls.domain.AclAuthorizationStrategyImpl;
import org.springframework.security.acls.domain.ConsoleAuditLogger;
import org.springframework.security.acls.domain.DefaultPermissionGrantingStrategy;
import org.springframework.security.acls.domain.SpringCacheBasedAclCache;
import org.springframework.security.acls.jdbc.BasicLookupStrategy;
import org.springframework.security.acls.jdbc.JdbcMutableAclService;
import org.springframework.security.acls.jdbc.LookupStrategy;
import org.springframework.security.acls.model.AclCache;
import org.springframework.security.acls.model.MutableAclService;
import org.springframework.security.acls.model.PermissionGrantingStrategy;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

@EnableCaching
@Configuration
public class SecurityAclConfig {

	@Bean
	public MutableAclService aclService(DataSource dataSource, LookupStrategy lookupStrategy, AclCache aclCache) {
		return new JdbcMutableAclService(dataSource, lookupStrategy, aclCache);
	}

	@Bean
	public LookupStrategy lookupStrategy(DataSource dataSource, AclCache aclCache,
			AclAuthorizationStrategy aclAuthorizationStrategy, PermissionGrantingStrategy grantingStrategy) {
		return new BasicLookupStrategy(dataSource, aclCache, aclAuthorizationStrategy, grantingStrategy);
	}

	@Bean
	public AclAuthorizationStrategy aclAuthorizationStrategy() {
		return new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_ADMIN"),
				new SimpleGrantedAuthority("gaModifyAuditing"), new SimpleGrantedAuthority("gaGeneralChanges"));
	}

	@Bean
	public PermissionGrantingStrategy grantingStrategy(ConsoleAuditLogger auditLogger) {
		return new DefaultPermissionGrantingStrategy(auditLogger);
	}

	@Bean
	public AclCache aclCache(Cache cache, PermissionGrantingStrategy grantingStrategy,
			AclAuthorizationStrategy aclAuthorizationStrategy) {
		return new SpringCacheBasedAclCache(cache, grantingStrategy, aclAuthorizationStrategy);
	}

	@Bean
	public Cache cache(CacheManager cacheManager) {
		return cacheManager.getCache("acl");
	}

	@Bean
	public ConsoleAuditLogger auditLogger() {
		return new ConsoleAuditLogger();
	}
}
